# ----------------------------------------------------------------------------
#       Copyright (C) 2013-2014 Huynh Vi Lam  <domovilam@gmail.com>
#
#       This file is part of pimucha.
#
#	This program is free software: you can redistribute it and/or modify
#	it under the terms of the GNU General Public License as published by
#	the Free Software Foundation, either version 3 of the License, or
#	(at your option) any later version.
#	
#	This program is distributed in the hope that it will be useful,
#	but WITHOUT ANY WARRANTY; without even the implied warranty of
#	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#	GNU General Public License for more details.
#	
#	You should have received a copy of the GNU General Public License
#	along with this program.  If not, see <http://www.gnu.org/licenses/>.
# ----------------------------------------------------------------------------

import logging
from piHAlibs import (my_fctname,coroutine)
from .parsers import CM15Parsers

logger = logging.getLogger()


def item2msgs(item):
    if not item[1].startswith('0x') : return None
    namedev = item[0]
    if 'CM15' not in namedev : return None
    sdata = item[1].split()
    hd = sdata[0]
    if hd not in ('0x5a','0x5d') : return None
    data = sdata[1:]
    model = 'NC'
    if hd == '0x5d':
        model = sdata[1]
        data = sdata[2:]
    logger.debug("Data to decode %s",repr(data))
    p = [ int(i,16) for i in data ]
    logger.debug("Packet to decode %s",repr(p))
    return [namedev,'x10', data, p, model,hd,item[1]]


@my_fctname
@coroutine
def CM15parser(decoders,rejected=None):
    """
    item = [namedev,events]
    split events (if several) before sending to CM15parser1
    """
    while True:
        events = (yield)
        logger.debug("Event receive %s",repr(events))
        evts = events[1].split('|')
        if len(evts) > 1:
            for event in evts:
                CM15parser1(decoders,rejected=None).send([events[0],event])
        else:
            CM15parser1(decoders,rejected=None).send(events)


@my_fctname
@coroutine
def CM15parser1(decoders,rejected=None):
    """
    Parse header for CM15
    item = [namedev,event]
    Send to next target = RF or PL decoder
    """
    hdps = CM15Parsers
    while True:
        item = (yield)
        logger.debug("Event receive %s",repr(item))
        msgs = item2msgs(item)
        if not msgs : continue
        if msgs[5] == '0x5a':
            for target in decoders:
                if 'x10pl' in target.__name__:
                    logger.debug("Data PL sent to decoder %s",repr(target))
                    target.send(msgs)
            continue
        #Case of RF event with msgs[5] == '0x5d'
        hdp = (msgs[5],msgs[4])
        if hdp not in hdps:
            if rejected: rejected.send(['NEW_PRORFX',hdp] + item)
            continue
        msgs[1] = hdps[hdp][0]		#protocol
        logger.debug("%s",repr(msgs))
        for target in decoders:
            if ('x10pl' not in target.__name__):
                logger.debug("Data RF sent to decoder %s",repr(target))
                target.send(msgs)


